package edu.gatech.startrader.gui;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import javax.swing.JFileChooser;
import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextPane;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JTable;
import javax.swing.UIManager;

import javax.swing.JInternalFrame;
import javax.swing.SwingConstants;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.table.DefaultTableModel;

import javax.swing.border.MatteBorder;

import edu.gatech.startrader.Game;
import edu.gatech.startrader.SaveState;
import edu.gatech.startrader.ship.Ship;
import edu.gatech.startrader.trade.TradeGood;
import edu.gatech.startrader.universe.Planet;

import java.awt.Color;
import java.awt.Panel;
import javax.swing.ImageIcon;
import java.awt.Font;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;

/**
 * MainGameScreen Class
 * This class contains the main game engine.
 * @author 
 *
 */
public class MainGameScreen extends JFrame{

	private JPanel contentPane;
	private JTable shipTable;
	private JTable cargoTable;
	private JTable passengerTable;
	private JTable planetResourcesTable;
	private JTable planetInfoTable;
	private Game game;
	/**
	 * Create the frame.
	 */
	public MainGameScreen(Game gameInfo) 
	{
        try {
            for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception e) {
        }
		game = gameInfo;
		setResizable(false);
		setTitle("Star Trader");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 850, 600);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JButton btnLoadGame = new JButton("Load Game");
		btnLoadGame.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) 
			{
				JFileChooser fc = new JFileChooser();
				int returnVal = fc.showSaveDialog(null);
				if(returnVal == JFileChooser.APPROVE_OPTION)
				{
					File file = new File(fc.getSelectedFile() + ".st");
					game = SaveState.load(file).getSaveInfo();
					repaint();
				}
			}
		});
		btnLoadGame.setBounds(356, 493, 137, 23);
		contentPane.add(btnLoadGame);
		
		JLabel lblPlanetInfo = new JLabel("Planet Info");
		lblPlanetInfo.setForeground(Color.YELLOW);
		lblPlanetInfo.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblPlanetInfo.setBounds(20, 382, 89, 14);
		contentPane.add(lblPlanetInfo);
		
		JLabel lblPassenger = new JLabel("Passenger");
		lblPassenger.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblPassenger.setForeground(Color.YELLOW);
		lblPassenger.setBounds(20, 198, 89, 14);
		contentPane.add(lblPassenger);
		
		JLabel lblShip = new JLabel("Ship");
		lblShip.setForeground(Color.YELLOW);
		lblShip.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblShip.setBounds(20, 10, 46, 14);
		contentPane.add(lblShip);
		
		JLabel lblCargo = new JLabel("Cargo");
		lblCargo.setForeground(Color.YELLOW);
		lblCargo.setBounds(174, 10, 46, 14);
		contentPane.add(lblCargo);
		
		JLabel lblPlanet = new JLabel("Planet Resources");
		lblPlanet.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblPlanet.setForeground(Color.YELLOW);
		lblPlanet.setBounds(174, 198, 121, 14);
		contentPane.add(lblPlanet);
		
		JButton btnSaveGame = new JButton("Save Game");
		btnSaveGame.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) 
			{
				JFileChooser fc = new JFileChooser();
				int returnVal = fc.showSaveDialog(null);
				if(returnVal == JFileChooser.APPROVE_OPTION)
				{
					File file = new File(fc.getSelectedFile() + ".st");
					SaveState.saveTo(file, game);
					repaint();
				}
			}
		});
		btnSaveGame.setBounds(356, 463, 137, 23);
		contentPane.add(btnSaveGame);
		
		JButton btnQuitGame = new JButton("Quit Game");
		btnQuitGame.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
			}
		});
		btnQuitGame.setBounds(356, 524, 137, 23);
		contentPane.add(btnQuitGame);
		
		JButton btnShipYard = new JButton("Ship Yard");
		btnShipYard.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				showShipYardScreen();
			}
		});
		btnShipYard.setBounds(727, 524, 107, 23);
		contentPane.add(btnShipYard);
		
		JButton btnWarp = new JButton("Warp");
		btnWarp.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				showWarpScreen();
			}
		});
		btnWarp.setBounds(727, 493, 107, 23);
		contentPane.add(btnWarp);
		
		JButton btnTrade = new JButton("Marketplace");
		
		btnTrade.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent arg0) 
			{
					TradeScreen.showTradeScreen(null, game.getPlayer(), game.getCurrentPlanet());
					repaint();
			}
		});
		btnTrade.setBounds(727, 463, 107, 23);
		contentPane.add(btnTrade);
		
		JLabel lblGalacticMap = new JLabel("Galactic Map");
		lblGalacticMap.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblGalacticMap.setForeground(Color.YELLOW);
		lblGalacticMap.setBounds(358, 10, 89, 14);
		contentPane.add(lblGalacticMap);
		
		JSeparator separator = new JSeparator();
		separator.setOrientation(SwingConstants.VERTICAL);
		separator.setBounds(345, 0, 3, 562);
		contentPane.add(separator);
		
		JSeparator separator_1 = new JSeparator();
		separator_1.setBounds(346, 447, 488, 2);
		contentPane.add(separator_1);
		
		JPanel mapPanel = new UniversePanel(game.getUniverse());
		mapPanel.setBorder(new MatteBorder(1, 1, 1, 1, new Color(0, 0, 0)));
		mapPanel.setBounds(352, 32, 484, 400);
		contentPane.add(mapPanel);
		
		shipTable = new JTable();
		shipTable.setFont(new Font("Tahoma", Font.PLAIN, 11));
		shipTable.setBackground(new Color(100, 149, 237));
		shipTable.setModel(new DefaultTableModel(
			new Object[][] {
				{"Type:", game.getPlayer().getShip().getType()},
				{"Fuel:", game.getPlayer().getShip().getFuel()},
				{"Hull:", game.getPlayer().getShip().getHull()},
				{"Escape Pod:", (game.getPlayer().getShip().hasEscapePod()) ? "Yes": "No"},
				{"Insured", (game.getPlayer().getShip().isInsured()) ? "Yes": "No"},
				{"Weapons:", "None"},
				{"Shields:", "None"},
				{"Gadgets:", "None"},
			},
			new String[] {
				"", ""
			}
		) {
			Class[] columnTypes = new Class[] {
				String.class, String.class
			};
			public Class getColumnClass(int columnIndex) {
				return columnTypes[columnIndex];
			}
			boolean[] columnEditables = new boolean[] {
				false, false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		shipTable.getColumnModel().getColumn(0).setPreferredWidth(80);
		shipTable.setBounds(20, 25, 138, 165);
		contentPane.add(shipTable);
		
		cargoTable = new JTable();
		cargoTable.setBackground(new Color(100, 149, 237));
		cargoTable.setBounds(170, 25, 163, 165);
		contentPane.add(cargoTable);
		
		passengerTable = new JTable();
		passengerTable.setBackground(new Color(100, 149, 237));
		passengerTable.setModel(new DefaultTableModel(
			new Object[][] {
				{null, null},
				{null, null},
				{null, null},
				{null, null},
			},
			new String[] {
				"", ""
			}
		));
		passengerTable.setBounds(20, 212, 138, 165);
		contentPane.add(passengerTable);
		
		TradeGood goods[] = TradeGood.values();
		Object[][] tableArray = new Object[goods.length][3];
		for(int i = 0; i < goods.length; i++)
		{
			tableArray[i][0] = goods[i].toString();
			tableArray[i][1] = game.getCurrentPlanet().getInventory().getAmount(goods[i]);
			tableArray[i][2] = "$"+game.getCurrentPlanet().getPrice(goods[i]);
		}
		planetResourcesTable = new JTable();
		planetResourcesTable.setBackground(new Color(100, 149, 237));
		planetResourcesTable.setModel(new DefaultTableModel(
			tableArray,
			new String[] {
				"Resource", "Quantity","Price"
			}
		) {
			Class[] columnTypes = new Class[] {
				String.class, Object.class, Object.class
			};
			public Class getColumnClass(int columnIndex) {
				return columnTypes[columnIndex];
			}
			boolean[] columnEditables = new boolean[] {
					false, false, false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		planetResourcesTable.setBounds(170, 212, 163, 165);
		contentPane.add(planetResourcesTable);
		
		planetInfoTable = new JTable();
		planetInfoTable.setBackground(new Color(100, 149, 237));
		planetInfoTable.setModel(new DefaultTableModel(
			new Object[][] {
				{"Name:", game.getCurrentPlanet().getName()},
				{"X-Cor:", new Integer((int) game.getCurrentPlanet().getX())},
				{"Y-Cor:", new Integer((int) game.getCurrentPlanet().getY())},
				{"Tech Level:", game.getCurrentPlanet().getTechLevel()},
				{"Conditions:", game.getCurrentPlanet().getSpecialResources()},
			},
			new String[] {
				"", ""
			}
		) {
			Class[] columnTypes = new Class[] {
				String.class, Object.class
			};
			public Class getColumnClass(int columnIndex) {
				return columnTypes[columnIndex];
			}
			boolean[] columnEditables = new boolean[] {
					false, false, false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		
		planetInfoTable.setBounds(20, 397, 313, 165);
		contentPane.add(planetInfoTable);
		
		JLabel lblBgimage = new JLabel("bgimage");
		lblBgimage.setForeground(Color.WHITE);
		lblBgimage.setIcon(new ImageIcon(MainGameScreen.class.getResource("/edu/gatech/startrader/gui/MainGameScreen.jpg")));
		lblBgimage.setBounds(-12, 0, 856, 572);
		contentPane.add(lblBgimage);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(157, 231, 6, 6);
		contentPane.add(scrollPane);
		repaint();
	}
	
	/**
	 * repaint method
	 * this method repaints after an update
	 */
	public void repaint()
	{
		Planet currentPlanet = game.getCurrentPlanet();
		planetInfoTable.setValueAt(currentPlanet.getName(), 0, 1);
		planetInfoTable.setValueAt((int)currentPlanet.getX(), 1, 1);
		planetInfoTable.setValueAt((int)currentPlanet.getY(), 2, 1);
		planetInfoTable.setValueAt(currentPlanet.getTechLevel(), 3, 1);
		planetInfoTable.setValueAt(currentPlanet.getSpecialResources(), 4 , 1);
		Ship playerShip = game.getPlayer().getShip();
		shipTable.setValueAt(playerShip.getType().toString(), 0, 1);
		shipTable.setValueAt(playerShip.getFuel(), 1 , 1);
		shipTable.setValueAt(playerShip.getHull(), 2, 1);
		shipTable.setValueAt((playerShip.hasEscapePod()) ? "Yes": "No", 3, 1);
		shipTable.setValueAt((playerShip.isInsured()) ? "Yes": "No", 3, 1);
		TradeGood goods[] = TradeGood.values();
		for(int i = 0; i < goods.length; i++)
		{
			planetResourcesTable.setValueAt(game.getCurrentPlanet().getInventory().getAmount(goods[i]), i, 1);
			planetResourcesTable.setValueAt("$"+game.getCurrentPlanet().getPrice(goods[i]), i, 2);
		}
		super.repaint();
	}
	
	/**
	 * showWarpScreen method
	 * this method shows the warp screen window
	 */
	public void showWarpScreen()
	{
		WarpScreen.showWarpScreen(this, game.getPlayer(), game.getUniverse());
	}
	
	public void showShipYardScreen()
	{
		ShipYardScreen.showShipYardScreen(this, game.getPlayer().getShip(), game.getCurrentPlanet());
	}

}
